<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="vue中axios如何实现token验证"/>




  <meta name="keywords" content="axios, vue, 八一" />



  <meta name="baidu-site-verification" content="HhUstaSjr0" />



  <meta name="google-site-verification" content="UA-102975942-1" />






  <link rel="alternate" href="/atom.xml" title="八一">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="https://bay1.top/2018/02/08/vue中axios如何实现token验证/"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />
<link rel="stylesheet" type="text/css" href="/css/prettify.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/sons-of-obsidian.css" media="screen" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  
  <script id="baidu_analytics">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9a885cc9fb6cd7bcef579deb8efe8a70";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script id="google_analytics">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-102975942-1', 'auto');
        ga('send', 'pageview');
  </script>










    <title> vue中axios如何实现token验证 - 八一 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">八一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/archives">
        <li class="mobile-menu-item">
          
          
            文章
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            标签
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            关于/友链
          
        </li>
      </a>
    
      <a href="/search">
        <li class="mobile-menu-item">
          
          
            站内搜索
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">八一</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives">
            
            
              文章
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              标签
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              关于/友链
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/search">
            
            
              站内搜索
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          vue中axios如何实现token验证
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2018-02-08
        </span>
        
        
        
      </div>
    </header>

    
    

    <div class="post-content">
      
        <p>继上篇实现Auth认证之后,然后每个跳转页面都会在后端验证token的存在<a id="more"></a><br>然后那天晚上通过模仿Auth发送请求,发送成功(上篇末尾的方式)<br>但是今天再继续写,发现每个页面请求都要发送token验证<br>就比较麻烦了</p>
<blockquote>
<p>这时候又要axios上场了<br>可以通过axios类似error拦截的方式拦截http request请求<br>这样每次request都可以默认加上token<br>(当然前提已经在session里存储了你的token验证字符串)</p>
</blockquote>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// main.js文件</span></span><br><span class="line"><span class="comment">// http request 拦截器</span></span><br><span class="line">axios.interceptors.request.<span class="keyword">use</span>(</span><br><span class="line">  config =&gt; &#123;</span><br><span class="line">    <span class="keyword">var</span> <span class="keyword">token</span> = sessionStorage.getItem('<span class="keyword">token</span>');</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">token</span>) &#123;  <span class="comment">// 判断是否存在token，如果存在的话，则每个http header都加上token</span></span><br><span class="line">      <span class="keyword">token</span> =sessionStorage.getItem('<span class="keyword">token</span>')+':';</span><br><span class="line">      config.headers.Authorization = `Basic <span class="variable">$&#123;new</span> Buffer(<span class="keyword">token</span>).<span class="keyword">toString</span>('base64')&#125;`;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> config;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">err</span> =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> Promise.reject(<span class="keyword">err</span>);</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<p>为什么要加”:”?<br>这里一开始我并没有加冒号,然后发现新加的request页面显示401<br>但是消息头里明明加上了Authorization,细看的话发现这个token和另外几个页面的不同<br>(因为另外几个页面的token是那天晚上的方式通过axios直接发送的)<br>解码正确的token发现是缺少冒号,具体原因不是很清楚<br>查看文档似乎发现了一个合理的解释(不知道是否正确)<br>文档中写到:</p>
<blockquote>
<p>新版的 verify_password 回调函数会尝试认证两次。首先它会把 username 参数作为令牌进行认证。如果没有验证通过的话，就会像基于密码认证的一样,验证username和password<br>然后文档curl例子类似下面的格式</p>
</blockquote>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">$ curl -u eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.<span class="string">XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc:</span>unused -i -X GET <span class="string">http:</span><span class="comment">//127.0.0.1:5000/api/resource</span></span><br><span class="line">HTTP/<span class="number">1.0</span> <span class="number">200</span> OK</span><br><span class="line">Content-<span class="string">Type:</span> application/json</span><br><span class="line">Content-<span class="string">Length:</span> <span class="number">30</span></span><br><span class="line"><span class="string">Server:</span> Werkzeug<span class="regexp">/0.9.4 Python/</span><span class="number">2.7</span><span class="number">.3</span></span><br><span class="line"><span class="string">Date:</span> Thu, <span class="number">28</span> Nov <span class="number">2013</span> <span class="number">20</span>:<span class="number">05</span>:<span class="number">08</span> GMT</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="string">"data"</span>: <span class="string">"Hello, miguel!"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们会看到这个 token:unused 的格式<br>然后request时会加上冒号</p>
</blockquote>

      
    </div>

    
      
      



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/axios/">axios</a>
            
              <a href="/tags/vue/">vue</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
      <a class="prev" href="/2018/03/08/WebSocket-Flask实现即时弹幕系统-开篇/">
        <i class="iconfont icon-left"></i>
        <span class="prev-text nav-default">WebSocket+Flask实现即时弹幕系统--开篇</span>
        <span class="prev-text nav-mobile">上一篇</span>
      </a>
    
    
      <a class="next" href="/2018/02/07/axios如何发送Basic-Auth/">
        <span class="next-text nav-default">axios如何发送Basic Auth</span>
        <span class="prev-text nav-mobile">下一篇</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div> 
    </div>
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="https://github.com/bay1" class="iconfont icon-github" title="github"></a>
        
      
    
      
        
          <a href="http://weibo.com/3190704711/profile?topnav=1&wvr=6&is_all=1" class="iconfont icon-weibo" title="weibo"></a>
        
      
    
      
    
      
    
      
    
    
    
  </div>


<div class="copyright">
  <span class="copyright-year">
    
    &copy; 
     
      2016 - 
    
    2018
    <span class="author">bay1</span>
  </span>
</div>
      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://bay1.top/2018/02/08/vue中axios如何实现token验证/';
        this.page.identifier = '2018/02/08/vue中axios如何实现token验证/';
        this.page.title = 'vue中axios如何实现token验证';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//https-blog-flywinky-top-1.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>



    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>
<script src="/js/prettify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('pre').addClass('prettyprint');
   prettyPrint();
 })
</script>
  </body>
</html>
